//
//  UIViewController+extension.m
//  NavigationBarTest
//
//  Created by Clavis on 2019/2/14.
//  Copyright © 2019 Clavis. All rights reserved.
//

#import "UIViewController+extension.h"
#import <objc/runtime.h>

@implementation UIViewController (extension)

+(void)load{
    //虽然load只执行一次，但是为了保险起见，我们还是给加个dispatch_once吧，良好的编程习惯，从这里开始
    static dispatch_once_t token;
    dispatch_once(&token, ^{

        SEL orginSel = @selector(viewWillAppear:);
        SEL overrideSel = @selector(overrideViewWillAppear:);

        Method originMethod = class_getInstanceMethod([self class], orginSel);
        Method overrideMethod = class_getInstanceMethod([self class], overrideSel);

        //原来的类没有实现指定的方法，那么我们就得先做判断，把方法添加进去，然后进行替换
        if (class_addMethod([self class], orginSel, method_getImplementation(overrideMethod) , method_getTypeEncoding(originMethod))) {
            class_replaceMethod([self class],
                                overrideSel,
                                method_getImplementation(originMethod),
                                method_getTypeEncoding(originMethod));

        }else{
            //交换实现
            method_exchangeImplementations(originMethod, overrideMethod);
        }
    });
}

- (void)overrideViewWillAppear:(BOOL)animation{
    //这里并不会造成死循环，因为这个时候是去调用原来的ViewWillAppear:(BOOL)animation方法了。
    NSLog(@"🌛 🌛 enter %@", self);
 
//    // 重置导航栏状态
    self.navigationController.navigationBar.barTintColor = UIColor.whiteColor;
    self.navigationController.navigationBar.prefersLargeTitles = NO;
    [self.navigationController setNavigationBarHidden:NO animated:animation];
    
    [self overrideViewWillAppear:animation];
}

@end
